package ru.ifmo.ipimenov.ewf_svn.standalone.ruler.impl;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import ru.ifmo.ipimenov.ewf_svn.standalone.model.RulesProvider;
import ru.ifmo.ipimenov.ewf_svn.standalone.model.StateProvider;
import ru.ifmo.ipimenov.ewf_svn.standalone.model.db.Document;
import ru.ifmo.ipimenov.ewf_svn.standalone.model.db.Rules;
import ru.ifmo.ipimenov.ewf_svn.standalone.model.db.State;
import ru.ifmo.ipimenov.ewf_svn.standalone.ruler.RulePerformer;
import ru.ifmo.ipimenov.ewf_svn.standalone.service.DocumentService;
import ru.ifmo.ipimenov.ewf_svn.standalone.service.impl.DocumentServiceImpl;

import java.util.List;

/**
 * @author: Ilya Pimenov
 * Scartel Starlab company
 */
public class SimpleRulePerformer implements RulePerformer {
    /**
     * Logger for all purposes
     */
    private static Log log = LogFactory.getLog(SimpleRulePerformer.class);

    public void performRule(State state, Document document) {
        DocumentService ds = new DocumentServiceImpl();

        List<Rules> rl = RulesProvider.getInstance().load(document);
        for (Rules r : rl) {
            String[] prepared = r.getRule().split(" ");
            if (prepared[0].equals(state.getName())) {
                log.info("RULE EXECTION " + r.getRule());
                Document d = ds.load(Integer.parseInt(prepared[1]));
                List<State> ls = StateProvider.getInstance().load(d.getCategory());
                int index = ls.indexOf(d.getState());
                if (prepared[2].equals("Up") && index < (ls.size() - 1)) {
                    index += 1;
                } else if (prepared[2].equals("Down") && index > 0) {
                    index -= 1;
                }
                State s = ls.get(index);
                log.info("RULE EXECUTION Document " + d.getName() + " state " + d.getState().getName() + " -> " + s.getName());
                ds.setState(d, s);
            }
        }
        log.info("Rule performed");
    }
}
